package org.dromara.system.utils;

import java.io.BufferedReader;

import java.nio.charset.StandardCharsets;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.system.domain.bo.GzhPushRecordBo;
import org.dromara.system.domain.bo.XcxSubscribeKeywordBo;
import org.dromara.system.domain.bo.XcxSubscribeProjectUnitBo;
import org.dromara.system.domain.bo.XcxSubscribeTemplateBo;
import org.dromara.system.domain.dto.TemplateMessage;
import org.dromara.system.domain.dto.WeChatTemplateMsg;
import org.dromara.system.domain.vo.GzhUserVo;
import org.dromara.system.domain.vo.XcxSubscribeKeywordVo;
import org.dromara.system.domain.vo.XcxSubscribeProjectUnitVo;
import org.dromara.system.domain.vo.XcxSubscribeTemplateVo;
import org.dromara.system.service.*;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;


/**
 * @Description 微信公众号http请求工具类
 * @author isymi
 * @version
 * @date 2023年5月29日下午4:07:39
 *
 */
@Validated
@RequiredArgsConstructor
@Slf4j
@Service
public  class WXPublicAccountHttpUtil {

    private final IGzhPushRecordService gzhPushRecordService;

    private final IXcxSubscribeTemplateService xcxSubscribeTemplateService;

    private final IXcxSubscribeProjectUnitService xcxSubscribeProjectUnitService;

    private final IXcxSubscribeKeywordService xcxSubscribeKeywordService;

    private final IGzhUserService gzhUserService;

    /**
     * 判断是否是否对应关键字
     * Keyword 物资名称 不能为空
     * projectUnit 公司名称 不能为空
     * usageScenarios 消息类型 分为 关注消息  关注关键字
     * projectName 项目名称
     * projectType 项目类型
     * projectStatus 项目状态
     */
    public void keywords(String keyword , String projectUnit,String usageScenarios,String projectName,String projectType,String projectStatus) throws IOException {
        if(StringUtils.isNotBlank(keyword)){ keyword = "  ";}
        if(StringUtils.isNotBlank(projectUnit)){ projectUnit = "  ";}
        List<Long> userIds1 = xcxSubscribeKeywordService.queryKeywordUserId(keyword, projectUnit);
        if (userIds1 != null && userIds1.size() > 0){
            //循环userid 给相关用户推送消息
            for (Long userid : userIds1){
                GzhUserVo gzhUserVo = gzhUserService.queryGzhById(userid);
                pushRecord(gzhUserVo,usageScenarios,keyword,projectUnit,projectName,projectType,projectStatus);
            }
        }
    }




    /**
     * 发送模板消息
     * usageScenarios ：关注消息  关键字  项目单位
     * gzhUserVo : 接收人
     *
     */
    public  void pushRecord(GzhUserVo gzhUserVo,String usageScenarios,String keyword,String projectUnit,String projectName,String projectType,String projectStatus) throws IOException {
        TemplateMessage templateMessage = new TemplateMessage();
        //设置发送人id
        templateMessage.setTouser(gzhUserVo.getOpenid());
        XcxSubscribeTemplateBo xcxSubscribeTemplateBo = new XcxSubscribeTemplateBo();
        xcxSubscribeTemplateBo.setUsageScenarios(usageScenarios);
        XcxSubscribeTemplateVo xcxSubscribeTemplateVo = xcxSubscribeTemplateService.queryByUsageScenarios(usageScenarios);
        //设置模板id
        templateMessage.setTemplate_id(xcxSubscribeTemplateVo.getTemplateId());
        templateMessage.setTopcolor("#FF0000");
        // key对应创建模板内容中的形参
        Map<String, WeChatTemplateMsg> data = new HashMap<String, WeChatTemplateMsg>();
        data.put("projectName", new WeChatTemplateMsg(projectName, "#173177"));
        data.put("projectType", new WeChatTemplateMsg(projectType, "#173177"));
        data.put("projectStatus", new WeChatTemplateMsg(projectStatus, "#173177"));
//        if(usageScenarios.equals("关注消息")){
//            data.put("projectName", new WeChatTemplateMsg(projectName, "#173177"));
//            data.put("projectType", new WeChatTemplateMsg(projectType, "#173177"));
//            data.put("projectStatus", new WeChatTemplateMsg(projectStatus, "#173177"));
//        } else if (usageScenarios.equals("关键字")){
//            data.put("projectName", new WeChatTemplateMsg(projectName, "#173177"));
//            data.put("projectType", new WeChatTemplateMsg(projectType, "#173177"));
//            data.put("projectStatus", new WeChatTemplateMsg(projectStatus, "#173177"));
//        }else if (usageScenarios.equals("项目单位")){
//            data.put("projectName", new WeChatTemplateMsg(projectName, "#173177"));
//            data.put("projectType", new WeChatTemplateMsg(projectType, "#173177"));
//            data.put("projectStatus", new WeChatTemplateMsg(projectStatus, "#173177"));
//        }
        templateMessage.setData(data);
        String token = GzhPushUtil.getToken();
        String pushStatus = sendMessage(token, templateMessage);
        GzhPushRecordBo gzhPushRecordBo = new GzhPushRecordBo();
        gzhPushRecordBo.setUserId(gzhUserVo.getId());
        gzhPushRecordBo.setKeyword(keyword);
        gzhPushRecordBo.setProjectUnit(projectUnit);
        gzhPushRecordBo.setPushStatus(pushStatus);
        gzhPushRecordService.insertByBo(gzhPushRecordBo);
    }


    /**
     * @Description 根据请求获取返回结果字符串（根据请求获取accessToken)
     * @date 2023年5月29日下午4:04:21
     * @param url
     * @return
     * @throws IOException
     */
    public static String get(String url) throws IOException {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            } else {
                // Handle error response
//                System.out.println("HTTP GET request failed with response code: " + responseCode);
                return null;
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * @Description 根据URl获取JSONObject：根据请求获取关注用户列表数据
     * @date 2023年5月29日下午4:02:16
     * @param token
     * @return
     * @throws IOException
     */
    public static JSONObject getJsonObject(String token) throws IOException {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        String url = "https://api.weixin.qq.com/cgi-bin/user/get?" + "access_token=" + token;

        try {
            URL urlObj = new URL(url);
            connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("GET");

            StringBuilder response = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            /**
             * 	正确返回的格式
             *      {
    					"total":2,
    					"count":2,
    					"data":{
    						"openid":["OPENID1","OPENID2"]},
    					"next_openid":"NEXT_OPENID"
					}
             */
            return JSON.parseObject(response.toString());
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    /**
     * @Description 获取关注用户的 openid 集合
     * @date 2023年5月29日下午4:04:02
     * @param token
     * @return
     * @throws IOException
     */
    public static  List<String> getOpenidList(String token) throws IOException {

        // 获取关注用户列表数据
        JSONObject jsonObject = getJsonObject(token);
//        System.out.println(jsonObject);

        // 错误情况
        if (jsonObject.containsKey("errcode")) {
            int errcode = jsonObject.getIntValue("errcode");
            String errmsg = jsonObject.getString("errmsg");
            throw new RuntimeException("Failed to get openid list. errcode: " + errcode + ", errmsg: " + errmsg);
        }

        int total = jsonObject.getIntValue("total");
        // 无用户关注 {"total":0,"count":0,"next_openid":""}
        if (total == 0) {
            throw new RuntimeException("没人关注");
        }
        // 有用户关注：
        JSONObject dataObject = jsonObject.getJSONObject("data");
        JSONArray openidArray = dataObject.getJSONArray("openid");

        // 将 openid 数组封装为 List 集合
        List<String> openidList = new ArrayList<>();
        for (int i = 0; i < openidArray.size(); i++) {
            String openid = openidArray.getString(i);
            openidList.add(openid);
        }
//        System.out.println("关注总人数："+ openidList.size());
        return openidList;
    }

    /**
     * @Description 发送消息
     * @date 2023年5月29日下午4:58:02
     * @param accessToken
     * @param templateMessage
     * @return
     * @throws IOException
     */
    public static String sendMessage( String accessToken, TemplateMessage templateMessage) throws IOException {
        String requestUrl ="https://api.weixin.qq.com/cgi-bin/message/template/send" + "?access_token=" + accessToken;
//        getTemplate(accessToken); 获取模板id
        URL urlObject = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        String requestBody = JSON.toJSONString(templateMessage);
        byte[] requestBodyBytes = requestBody.getBytes(StandardCharsets.UTF_8);
        connection.setRequestProperty("Content-Length", String.valueOf(requestBodyBytes.length));
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(requestBodyBytes);
        outputStream.close();
        int responseCode = connection.getResponseCode();
        BufferedReader reader;
        if (responseCode >= 200 && responseCode <= 299) {
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } else {
            reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        }
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        connection.disconnect();
//        System.out.println("Response Code: " + responseCode); 返回状态码
//        System.out.println("Response Body: " + response.toString());

        return String.valueOf(responseCode);
    }
}
